<template>

	<view class="page">

		<uni-card v-if="showHeader" margin='2px' style="margin-bottom: 10px; padding: 5px;">
			<mpopupHeaderItem label="经营者名称" :value="orderList.operatorName" height="60px" />
			<mpopupHeaderItem label="地址" :value="orderList.address" height="60px" />
			<mpopupHeaderRadioItem label="申请经营业态" :custom-class="'custom-align'" :custom-style="{ padding: '20rpx' }">
				<uni-data-checkbox selectedColor="blue" selectedTextColor="blue" mode='list'
					v-model="orderList.businessFormat" @change="formatRadiochange"
					:localdata="formatItem"></uni-data-checkbox>
			</mpopupHeaderRadioItem>
			<mpopupHeaderRadioItem label="申请经营项目" :custom-class="'custom-align'" :show-bottom-border="true"
				:custom-style="{ padding: '20rpx' }">
				<uni-data-checkbox selectedColor="blue" selectedTextColor="blue" mode='list'
					v-model="orderList.businessProject" @change="projectRadiochange"
					:localdata="projectItem"></uni-data-checkbox>
			</mpopupHeaderRadioItem>
		</uni-card>
		<view>
			<uni-card class="mpopup" margin='2px' style="margin-bottom: 10px; padding: 5px;">
				<mpopupTable v-if="!isBlankPage" :data-list="currentPageData" @check-change="handleCheckChange"
					@remark-click="handleRemark" />


				<!-- 独立空白页 -->
				<view v-else class="blank-page">
					<view>
						<uni-card margin='2px' style="margin-bottom: 15px; padding: 5px;text-align: center;">
							<view class="card-title">核查结果</view>
							<view class="card-content">
								检查项目总数
								<text class="custom-text">{{ totalCheckItems }}</text>
								项，不符合项目总数
								<text class="custom-text">{{ unqualifiedItems }}</text>
								项。
							</view>
						</uni-card>
						<uni-card margin='2px' style="margin-bottom: 10px; padding: 5px;text-align: center;">
							<view class="card-title">核查意见</view>
							<view class="card-content">
								<view>{{checkPersion}} <text class="custom-text" @click="setPersonnelName">
										{{ orderList.checkPersonnelName || '点击添加核查人员【可编辑多人】' }}
									</text> {{checkTitle}}
								</view>
								<view>
								</view>

							</view>
							<mpopupHeaderRadioItem :show-bottom-border="true" label="核查意见"
								:custom-class="'custom-align'" :custom-style="{ padding: '20rpx' }">
								<uni-data-checkbox v-model="orderList.checkOpinion" selectedColor="blue"
									selectedTextColor="blue" mode='list' :localdata="checkOpiniion"
									@change="modeChange"></uni-data-checkbox>
							</mpopupHeaderRadioItem>


							<!-- 虚线容器 -->
							<view class="dashed-box2">
								<!-- 动态签名列 -->
								<view v-for="(sign, index) in orderList.workOrderSignatureList" :key="index"
									class="custom-title">

									<view
										style="width:100px;color: black;font-size: 16px;font-weight: bold;text-align: right; margin-right:20px;">
										{{sign.signaturePosition}}
									</view>

									<signInput :initialImage="sign.signature" bgColor="#ffffff" :action="action"
										@signToUrl="(url) => handleSignUpload(url, index)"></signInput>
								</view>

								<!-- 添加签名列按钮 -->
								<view class="dashed-box3" @click="addSignColumn">
									<text style="font-size: 20rpx;font-weight: bold;">+点此添加更多签字栏</text>
								</view>

								<!-- 核查人员日期 -->
								<view class="custom-dateText">
									<text @click="openDatePicker('checkPerson')"
										class="custom-text3">{{ this.orderList.checkSignDate || '选择日期' }}</text>
								</view>
							</view>
							<!-- 虚线容器 -->
							<view class="dashed-box2">
								<!-- 标题行 -->
								<view class="custom-title">
									<text
										style="margin-right: 20px;color: black;font-size: 20px;font-weight: bold;">食品经营单位负责人签字</text>
									<signInput bgColor="#ffffff" ref="sign" :initialImage='orderList.foodPersonSign'
										:action="action" @signToUrl="signToUrl3">
									</signInput>
								</view>
								<!-- 食品单位日期 -->
								<view class="custom-dateText">
									<text @click="openDatePicker('foodate')"
										class="custom-text3">{{ this.orderList.foodPersonDate || '选择日期' }}</text>
								</view>

							</view>
						</uni-card>
					</view>
				</view>
			</uni-card>
			<!-- 分页器 -->
			<cc-listPageView :totalNum="totalNum + pageSize" :pageCount="pageSize" :curPageNum="curPageNum"
				@submit="submitForm('1')" @save="submitForm('0')" @backToHome="handleBackToHome"
				@pageClick="handlePageChange">
			</cc-listPageView>

			<uni-popup ref="personnelPopup" type="dialog">
				<uni-popup-dialog mode="input" title="填写核查人员" :value="checkPersonnelNames"
					@confirm="handlePersonnelConfirm">
					<view class="multi-input-container">
						<view v-for="(item,index) in checkPersonnelList" :key="index">
							<uni-easyinput v-model="item.name" placeholder="请输入姓名" :clearable="false">
								<template #right>
									<uni-icons type="minus" size="24" color="#ff0000" @click="removePersonnel(index)"
										v-if="checkPersonnelList.length > 1"></uni-icons>
								</template>
							</uni-easyinput>
						</view>
						<uni-icons type="plus" size="24" color="#007AFF" @click="addPersonnel"></uni-icons>
					</view>
				</uni-popup-dialog>
			</uni-popup>

			<!-- 添加日期选择弹窗 -->
			<uni-popup ref="datePopup" type="dialog">
				<uni-popup-dialog mode="base" title="选择日期" @confirm="handleDialogConfirm" @close="handleDialogClose">
					<uni-datetime-picker type="date" @change="handleDateChange" />
				</uni-popup-dialog>
			</uni-popup>


			<!-- 输入弹窗 -->
			<uni-popup ref="childPopup" type="dialog">
				<uni-popup-dialog mode="base" title="输入其他信息" @confirm="handledChildConfirm" @close="handleChildClose">
					<uni-data-checkbox selectedColor="blue" selectedTextColor="blue" mode='list' :localdata="childItem"
						@change="onCheckboxChange"></uni-data-checkbox>
				</uni-popup-dialog>
			</uni-popup>

			<!-- 输入弹窗 -->
			<uni-popup ref="child2Popup" type="dialog">
				<uni-popup-dialog mode="base" title="输入其他信息" @confirm="handledChildConfirm2" @close="handleChildClose2">
					<uni-data-checkbox selectedColor="blue" selectedTextColor="blue" mode='list' :localdata="childItem2"
						@change="onCheckboxChange2"></uni-data-checkbox>
				</uni-popup-dialog>
			</uni-popup>
		</view>
	</view>
</template>

<script>
	import signInput from "@/components/am-sign-input/am-sign-input.vue"
	import mpopupHeaderItem from "@/components/mpopup-header-item.vue"
	import mpopupHeaderRadioItem from "@/components/mpopup-header-radio-item.vue"
	import mpopupTable from "@/components/mpopup-table.vue"
	import {
		categoryInfo,
		getformat,
		getProject,
		addCategory,
		getMedicalDict,
		categoryUpdate
	} from '@/api/order'
	import {
		getFoodReport
	} from '@/api/report.js'
	export default {
		components: {
			signInput,
			mpopupHeaderRadioItem,
			mpopupHeaderItem, // 需先导入组件
			mpopupTable
		},
		data() {
			return {
				orderList: {
					operatorName: '',
					address: '',
					bidType: '',
					businessFormat: '',
					businessProject: '',
					checkCount: 0,
					checkNoConform: 0,
					checkOpinion: 0,
					orderTableResultList: [],
					auditStatus: 0,
					workOrderSignatureList: [],
					orderCategory: '',
					checkPersonnelName:''
				},

				// 签名列数据
				childItem: {},
				childItem2: {},
				checkPersion: '',
				checkTitle: '',


				currentDate: '',
				checkPersonnelList: [{
					name: ''
				}], // 人员列表
				checkPersonnelNames: '', // 显示用文本
				action: "https://8954wg323mw0.vicp.fun/app/upload/imageFile", //上传服务器的地址
				header: {}, //图片上传携带头部信息
				showHeader: true,
				pageSize: 5, // 每页显示5条
				totalNum: 0,
				curPageNum: 1,
				sourceData: [], // 原始数据
				currentPageData: [], // 当前页数据
				pageCache: new Map(),
				operatorName: '',
				address: '',
				workOrderId: '',
				checkPersonnelSign: '',
				checkPersonnelSign2: '',
				foodPersonSign: '',
				checkPersonnelName: '小郭', //[核查人员姓名,可编辑多人]
				opinion: '', // 核查意见

				formatRadio: '',
				projectRadio: '',
				formatItem: [],
				checkOpiniion: [],
				projectItem: [], // 核查人员日期
				checkSignDate: '',
				foodPersonDate: '',
				editDateType: '',

				selectedChildren: new Map(), // 存储父项value对应的选中子项value
				tempParentItem: null, // 临时存储当前操作的父项
				selectedChildrenProject: new Map(), // 经营项目的父子关系
				tempParentItemProject: null, // 当前操作的经营项目父项
				editStatus: 'ADD',

			}
		},
		onLoad(options) {
			if (options.editStatus != null) {
				const editStatus = decodeURIComponent(options.editStatus);
				const workOrderId = decodeURIComponent(options.workOrderId);
				this.getcategoryInfo(workOrderId);
				this.editStatus = options.editStatus;
			} else {
				// 获取URL参数
				const operatorName = decodeURIComponent(options.operatorName);
				const address = decodeURIComponent(options.address);
				const orderid = decodeURIComponent(options.workOrderId);
				this.orderList.operatorName = operatorName;
				this.orderList.address = address;
				this.orderList.workOrderId = orderid;
				this.foodReport()
			}

			const orderCategory = decodeURIComponent(options.orderCategory);
			this.orderList.orderCategory = orderCategory;

			this.getMedicalDict('business_project'),

				this.getMedicalDict('business_format')
			//检查意见内容	
			this.getMedicalDict('check_opinion_text')
			//检查结果	
			this.getMedicalDict('check_opiniion')


		},
		computed: {
			// 判断是否是空白页
			isBlankPage() {
				const dataPages = Math.ceil(this.orderList.orderTableResultList.length / this.pageSize)
				return this.curPageNum > dataPages
			},
			totalCheckItems() {
				return this.orderList.orderTableResultList.length;
				// return this.orderList.orderTableResultList.filter(item => item.delFlag === 1).length
			},
			unqualifiedItems() {
				return this.orderList.orderTableResultList.filter(item => [1].includes(item.result)).length
			}
		},
		methods: {
			// 添加签名列
			addSignColumn() {
				uni.showModal({
					title: '添加人员签名',
					content: '',
					editable: true,
					success: ({
						content
					}) => {
						this.orderList.workOrderSignatureList.push({
							signature: '',
							signaturePosition: content,
							createBy: '管理员'
						});
					}
				});


			},

			// 处理签名上传（改造后）
			handleSignUpload(res, index) {
				try {
					
					const response = JSON.parse(res.data)
					if (response.code === 0) {
						this.$set(this.orderList.workOrderSignatureList, index, {
							...this.orderList.workOrderSignatureList[index],
							signature: response.data, // ✅ 正确提取data字段
							createBy: '系统管理员'
						})
					} else {
						uni.showToast({
							title: response.msg,
							icon: 'none'
						})
					}
				} catch (e) {
					console.error('签名数据解析失败:', e)
					uni.showToast({
						title: '签名数据异常',
						icon: 'none'
					})
				}

				console.log('签名更新成功:', this.orderList.workOrderSignatureList)
			},
			//获取字典值
			async getMedicalDict(type) {

				try {
					const res = await getMedicalDict(type)
					// 增加响应状态判断
					if (res.code === 0) { //获取经营项目方法
						if (type === 'business_project') {
							this.projectItem = res.data.map(item => ({
								text: item.label,
								value: item.value,
								remark: item.remark
							}));

							// 并发获取二级数据
							this.projectItem = await Promise.all(
								this.projectItem.map(async item => {
									if (item.remark) {
										try {
											const subData = await getMedicalDict(item.remark)
											return {
												...item,
												children: subData.data
											}
										} catch (e) {
											console.error('子接口请求失败', e)
											return {
												...item,
												children: []
											} // 失败时保留父级数据
										}
									}
									return item
								})
							)
							this.projectItem = this.projectItem.map(item => {
								// 有 children 的情况
								if (item.children && item.children.length > 0) {
									// 拼接 children 的 label（每个前加 O）
									const childrenLabels = item.children.map(child => `  〇  ${child.label}`)
										.join(
											' ');

									// 返回新对象（保留原有属性，仅修改 text）
									return {
										...item,
										text: `${item.text} ${childrenLabels}`
									};
								}
								// 没有 children 直接返回原对象
								return item;
							});

							console.log("组装的数据1" + JSON.stringify(this.projectItem))

							this.radio1 = this.projectItem[0]?.value || '';
						} else if (type === 'business_format') {
							// 格式化数据结构
							this.formatItem = res.data.map(item => ({
								text: item.label,
								value: item.value,
								remark: item.remark
							}));

							// 并发获取二级数据
							this.formatItem = await Promise.all(
								this.formatItem.map(async item => {
									if (item.remark) {
										try {
											const subData = await getMedicalDict(item.remark)
											return {
												...item,
												children: subData.data
											}
										} catch (e) {
											console.error('子接口请求失败', e)
											return {
												...item,
												children: []
											} // 失败时保留父级数据
										}
									}
									return item
								})
							)

							this.formatItem = this.formatItem.map(item => {
								// 有 children 的情况
								if (item.children && item.children.length > 0) {
									// 拼接 children 的 label（每个前加 O）
									const childrenLabels = item.children.map(child => `  〇 ${child.label}`)
										.join(
											' ');
									// 返回新对象（保留原有属性，仅修改 text）
									return {
										...item,
										text: `${item.text} ${childrenLabels}`
									};
								}
								// 没有 children 直接返回原对象
								return item;
							});
							console.log("组装的数据2" + JSON.stringify(this.formatItem))
							// 初始化默认选中项（可选）
							this.radio1 = this.formatItem[0]?.value || '';
						} else if (type === 'check_opinion_text') {

							this.checkPersion = res.data[0].label; // ✅ 用 this 赋值
							this.checkTitle = res.data[1].label;

							console.log(res.data)
						} else if (type === 'check_opiniion') {

							this.checkOpiniion = res.data.map(item => ({
								text: item.label + '   (' + item.remark + ')',
								value: parseInt(item.value)

							}));

							console.log('ddd' + JSON.stringify(this.checkOpiniion))

						}
					} else {
						throw new Error(res?.data?.msg || '接口返回异常')
					}
				} catch (error) {
					uni.showToast({
						title: error.message || '获取失败',
						icon: 'none',
						duration: 2000
					})
				}
			},


			// 在获取数据时为每个条目添加唯一ID（修改foodReport方法）
			async foodReport() {
				const res = await getFoodReport('1');
				if (res.code === 0) {
					console.log(res);
					this.orderList.orderTableResultList = res.data.map((item, index) => ({
						uniqueId: Math.random().toString(36).substr(2), // 添加唯一ID
						originalIndex: index, // 保留原始索引
						...item,
						sort: index + 1,
						result: parseInt(item.result || 0),
						fileName: item.fileInfo,
						remark: ''
					}));

					this.orderList.workOrderSignatureList.push({ // 第一条
						signature: '',
						signaturePosition: '核查人员',
						createBy: '管理员'
					}, { // 第二条
						signature: '',
						signaturePosition: '核查人员',
						createBy: '管理员'
					});
					this.totalNum = this.orderList.orderTableResultList.length;
					this.loadPageData(1);
				}
			},
			// 获取工单详情
			async getcategoryInfo(orderId) {
console.log("this.orderList" + orderId)
				const res = await categoryInfo(orderId);
				if (res.code === 0) {
					this.orderList = res.data;
					this.orderList.checkOpinion = parseInt(this.orderList.checkOpinion);

					console.log("this.orderList" + JSON.stringify(this.orderList))
					this.orderList.orderTableResultList = this.orderList.orderTableResultList.map((item, index) => ({
						uniqueId: Math.random().toString(36).substr(2), // 添加唯一ID
						originalIndex: index, // 保留原始索引
						...item,
						sort: index + 1,
						result: parseInt(item.result || 0),
						fileName: item.fileInfo
					}));

					this.totalNum = this.orderList.orderTableResultList.length;
					this.loadPageData(1);
				}
			},
			// 打开日期选择器
			openDatePicker(type) {
				this.editDateType = type;
				this.$refs.datePopup.open();
			},
			// 日期变化暂存
			handleDateChange(e) {
				this.tempDate = e ? new Date(e) : null;
			}, // 弹窗确认
			// 修改handleDialogConfirm方法
			handleDialogConfirm() {
				if (this.tempDate) {
					const year = this.tempDate.getFullYear();
					const month = (this.tempDate.getMonth() + 1).toString().padStart(2, '0');
					const day = this.tempDate.getDate().toString().padStart(2, '0');
					const formattedDate = `${year}-${month}-${day}`;
					if (this.editDateType === 'checkPerson') {
						this.orderList.checkSignDate = formattedDate;
					} else {
						this.orderList.foodPersonDate = formattedDate;
					}

				}

				this.$refs.datePopup.close();
			},
			// 弹窗关闭
			handleDialogClose() {
				this.currentEditType = null;
				this.tempDate = null;
				this.$refs.datePopup.close();
			},
			// 获取当前日期字符串（用于初始化）
			getCurrentDateString() {
				const date = new Date();
				return `${date.getFullYear()}-${(date.getMonth()+1).toString().padStart(2,'0')}-${date.getDate().toString().padStart(2,'0')}`;
			},

			// 日期确认处理
			handleDateConfirm(e) {
				const date = new Date(e);
				const year = date.getFullYear();
				const month = (date.getMonth() + 1).toString().padStart(2, '0');
				const day = date.getDate().toString().padStart(2, '0');

				if (this.currentEditType) {
					const {
						type,
						field
					} = this.currentEditType;
					const target = type === 'check' ? this.checkDate : this.foodDate;

					// 更新全部日期字段
					target.year = year;
					target.month = month;
					target.day = day;
				}

				this.$refs.datePopup.close();
				this.currentEditType = null;

			},
			// 打开弹窗
			openPersonnelEditor() {

				this.$refs.personnelPopup.open()
			},

			// 确认保存
			handlePersonnelConfirm() {
				this.checkPersonnelNames = this.checkPersonnelList
					.filter(item => item.name.trim())
					.map(item => item.name)
					.join('、')
				this.$refs.personnelPopup.close()
			},

			// 添加人员
			addPersonnel() {
				this.checkPersonnelList.push({
					name: ''
				})
			},

			// 删除人员
			removePersonnel(index) {
				this.checkPersonnelList.splice(index, 1)
			},

			handledChildConfirm(e) {
				this.$refs.childPopup.close();
			},
			handleChildClose(e) {
				this.$refs.childPopup.close();
			},
			handledChildConfirm2(e) {
				this.$refs.child2Popup.close();
			},
			handleChildClose2(e) {
				this.$refs.child2Popup.close();
			},
			// 经营业态单选变化
			formatRadiochange(e) {
				console.log("ccc")
				const parentItem = e.detail.data;
				// 清除当前父项之前的子项选择
				if (this.tempParentItem && this.tempParentItem.value !== parentItem.value) {
					this.selectedChildren.delete(this.tempParentItem.value);
					this.childItem = []; // 清空当前子项列表
				}
				this.tempParentItem = parentItem;

				if (parentItem.children?.length) {
					// 生成带取消选项的子项列表
					this.childItem = [
						...parentItem.children.map(child => ({
							text: child.label,
							value: child.value,
							selected: this.selectedChildren.get(parentItem.value) === child.value
						})),
						{
							text: '取消选择',
							value: 'CANCEL_FLAG',
							customStyle: 'color: #ff0000;'
						}
					];

					this.$refs.childPopup.open();
				} else {
					// 没有子项直接更新父项值
					//this.orderList.bidType = parentItem.value;
					this.updateParentDisplay(parentItem.value);
				}
			},
			// 子项复选框变化
			onCheckboxChange(e) {
				const selectedValue = e.detail.value;
				const parentValue = this.tempParentItem.value;

				if (selectedValue === 'CANCEL_FLAG') {
					// 清除当前父项的子项选择
					this.selectedChildren.delete(parentValue);
				} else {
					// 更新当前父项的子项选择
					this.selectedChildren.set(parentValue, selectedValue);
				}
				this.updateParentDisplay(parentValue);
				this.$refs.childPopup.close();
			},
			// 更新父项显示文本
			updateParentDisplay(currentParentValue) {
				this.formatItem = this.formatItem.map(parent => {
					let displayText = parent.text.split(' 〇')[0];

					if (parent.children) {
						const currentChild = this.selectedChildren.get(parent.value);
						const childrenText = parent.children.map(child => {
							const isSelected = child.value === currentChild;
							return `  ${isSelected ? '☑' : '〇'} ${child.label}`;
						}).join(' ');

						// 添加状态提示
						const statusTip = currentChild ? '' : ' (待选择子项)';
						displayText = `${displayText}${childrenText}${statusTip}`;
					}

					return {
						...parent,
						text: displayText,
						// 保持父项选中状态
						_selected: parent.value === currentParentValue
					};
				});
				this.$forceUpdate();
			},

			// 经营项目单选变化
			projectRadiochange(e) {
				const parentItem = e.detail.data;
				// 清除当前父项之前的子项选择
				if (this.tempParentItemProject && this.tempParentItemProject.value !== parentItem.value) {
					this.selectedChildrenProject.delete(this.tempParentItemProject.value);
					this.childItem2 = []; // 清空当前子项列表
				}
				this.tempParentItemProject = parentItem;

				if (parentItem.children?.length) {
					// 生成带取消选项的子项列表
					this.childItem2 = [
						...parentItem.children.map(child => ({
							text: child.label,
							value: child.value,
							selected: this.selectedChildrenProject.get(parentItem.value) === child.value
						})),
						{
							text: '取消选择',
							value: 'CANCEL_FLAG',
							customStyle: 'color: #ff0000;'
						}
					];

					this.$refs.child2Popup.open();
				} else {
					// 没有子项直接更新父项值
					//this.orderList.bidType = parentItem.value;
					this.updateParentDisplay2(parentItem.value);
				}
			},
			// 子项复选框变化
			onCheckboxChange2(e) {

				const selectedValue = e.detail.value;
				const parentValue = this.tempParentItemProject.value;

				if (selectedValue === 'CANCEL_FLAG') {
					// 清除当前父项的子项选择
					this.selectedChildrenProject.delete(parentValue);
				} else {
					// 更新当前父项的子项选择
					this.selectedChildrenProject.set(parentValue, selectedValue);
				}
				this.updateParentDisplay2(parentValue);
				this.$refs.child2Popup.close();
			},
			// 更新父项显示文本
			updateParentDisplay2(currentParentValue) {

				this.projectItem = this.projectItem.map(parent => { // ✅ 改为操作 projectItem
					let displayText = parent.text.split(' 〇')[0];

					if (parent.children) {
						const currentChild = this.selectedChildrenProject.get(parent.value);
						const childrenText = parent.children.map(child => {
							const isSelected = child.value === currentChild;
							return `  ${isSelected ? '☑' : '〇'} ${child.label}`;
						}).join(' ');

						// 添加状态提示
						const statusTip = currentChild ? '' : ' (待选择子项)';
						displayText = `${displayText}${childrenText}${statusTip}`;
					}

					return {
						...parent,
						text: displayText,
						// 保持父项选中状态
						_selected: parent.value === currentParentValue
					};
				});
				this.$forceUpdate();
			},
			/**
			 * @param {Object} e
			 * 返回的签名地址
			 */
			signToUrl(e) {
				if (e.error_code && e.error_code === '201') {
					uni.showToast({
						title: e.msg,
						icon: 'none'
					})
					return
				}
				// 1. 解析响应数据（假设 e.data 是 JSON 字符串）
				const response = JSON.parse(e.data)
				console.log(response.data);
				this.checkPersonnelSign = response.data;
			},
			/**
			 * @param {Object} e
			 * 返回的签名地址
			 */
			signToUrl2(e) {
				if (e.error_code && e.error_code === '201') {
					uni.showToast({
						title: e.msg,
						icon: 'none'
					})
					return
				}
				const response = JSON.parse(e.data)
				console.log(response.data);
				this.checkPersonnelSign2 = response.data;

			},
			/**
			 * @param {Object} e
			 * 返回的签名地址
			 */
			signToUrl3(e) {
				if (e.error_code && e.error_code === '201') {
					uni.showToast({
						title: e.msg,
						icon: 'none'
					})
					return
				}
				const response = JSON.parse(e.data)

				this.orderList.foodPersonSign = response.data;

			},
			// 返回首页处理
			handleBackToHome() {
				this.curPageNum = 1 // 修正变量名
				this.loadPageData(1) // 必须传递页码参数
				this.pageCache.clear() // 建议清空缓存
				// 根据页码控制表头显示
				this.showHeader = true;
			},
			handleSign(type) {
				uni.showActionSheet({
					itemList: ['选择相册图片', '手写签名'],
					success: (res) => {
						if (res.tapIndex === 0) this.chooseImage();
						else if (res.tapIndex === 1) this.openSignaturePad(type);
					}
				});
			},
			chooseImage() {
				uni.chooseImage({
					count: 1,
					success: (res) => {
						const tempPath = res.tempFilePaths[0];
						this.uploadSignature(tempPath); // 调用上传逻辑
					}
				});
			},

			// 生成提交数据
			generateSubmitData(status) {
				return {
					workOrderId: this.workOrderId, //订单号
					operatorName: this.operatorName, //经营者名称
					address: this.address, //地址
					businessFormat: this.formatRadio, //选中业态
					businessProject: this.projectRadio, //选中项目
					checkCount: this.orderList.orderTableResultList.length, //总检查项数
					checkNoConform: this.unqualifiedItems, //不符合项数
					checkPersonnelName: this.checkPersonnelNames,
					checkOpinion: this.opinion,
					checkPersonnelSign: this.checkPersonnelSign,
					checkPersonnelSignOne: this.checkPersonnelSign2,
					checkSignDate: this.checkSignDate,
					foodPersonSign: this.foodPersonSign,
					foodPersonDate: this.foodPersonDate,
					auditStatus: status,
					createBy: "系统管理员",
					orderTableResultList: this.orderList.orderTableResultList.map(item => ({
						templateId: item.templateId,
						result: item.delFlag,
						fileInfo: item.fileUrl,
						remarks: item.remark || "",
						createBy: "系统管理员"
					}))
				}
			},
			// 生成提交数据
			generateSubmitData2(status) {
				console.log(this.orderList)
			},
			// 提交方法
			submitForm(status) {

				
				if (this.editStatus == 'FALSE') {
					// 处理失败情况
					uni.showToast({
						title: '当前处于查看状态',
						icon: 'none'
					});
				}

				if (this.editStatus === 'EDIT') {
						
					this.UPDATE(status);
				}

				if (this.editStatus === 'ADD') {
					this.ADD(status);
				}



			},
			//添加
			async ADD(status) {
				this.orderList.auditStatus = status;
				const res = await addCategory(this.orderList);
				if (res.code === 0) {
					// 显示成功提示 
					uni.showToast({
						title: '提交成功',
						icon: 'success',
						duration: 1500
					});
				// 关闭当前页面，跳转到工单页
				this.$closeAndRedirect({
				  url: '/pages/work/history/index'
				});
				} else {
					// 处理失败情况
					uni.showToast({
						title: res.msg || '提交失败',
						icon: 'none'
					});
				}
			},
			//修改
			async UPDATE(status) {
				this.orderList.auditStatus = status;
			
				const res = await categoryUpdate(this.orderList);
				if (res.code === 0) {
					// 显示成功提示
					uni.showToast({
						title: '提交成功',
						icon: 'success',
						duration: 1500
					});
					
				// 关闭当前页面，跳转到工单页
				this.$closeAndRedirect({
				  url: '/pages/work/history/index'
				});
				} else {
					// 处理失败情况
					uni.showToast({
						title: res.msg || '提交失败',
						icon: 'none'
					});
				}
			},
			// 修正后的数据加载方法
			loadPageData(pageNum) {

				const dataPages = Math.ceil(this.orderList.orderTableResultList.length / this.pageSize)

				if (pageNum > dataPages) {
					this.currentPageData = [] // 清空表格数据
					return // 不加载数据
				}

				// 强制更新当前页码
				this.curPageNum = pageNum

				// 优先从缓存读取
				if (this.pageCache.has(pageNum)) {
					this.currentPageData = this.pageCache.get(pageNum)
					return
				}

				// 计算分页（添加边界保护）
				const start = Math.max(0, (pageNum - 1) * this.pageSize)
				const end = Math.min(start + this.pageSize, this.orderList.orderTableResultList.length)

				// 确保数据存在
				if (start >= this.orderList.orderTableResultList.length) {
					this.currentPageData = []
					return
				}

				const pageData = this.orderList.orderTableResultList.slice(start, end)

				// 更新数据和缓存
				this.pageCache.set(pageNum, pageData)
				this.currentPageData = pageData
			},
			handlePageChange(tag) {
				const maxDataPage = Math.ceil(this.orderList.orderTableResultList.length / this.pageSize);
				let newPage = this.curPageNum;
				if (tag === 0) {
					newPage = Math.max(1, newPage - 1);
				} else {
					newPage = Math.min(maxDataPage + 1, newPage + 1); // 包含空白页
				}

				if (newPage !== this.curPageNum) {
					this.curPageNum = newPage;
					this.loadPageData(newPage);

					// 根据页码控制表头显示
					this.showHeader = newPage === 1;
				}
			},
			handleCheckChange(item) {
				console.log('选项变更:', item)
				// 这里可以添加自动保存逻辑
			},

			// 复选框经营业态方法处理
			handleCheckFormatChange(item) {
				console.log('选中值:', this.radio1);
				// 自动保存逻辑示例
				this.saveSelection({
					fieldType: item.type, // 业态或项目类型标识
					selectedValue: this.radio1
				});
			},
			// 复选框项目方法处理
			handleCheckProjectChange(item) {
				console.log('选中值:', this.radio1);

			},
			// handleRemark 方法修正
			handleRemark(item) {
				uni.showModal({
					title: '添加备注',
					content: item.remarks || '',
					editable: true,
					success: ({
						content
					}) => {
						const target = this.orderList.orderTableResultList.find(i => i.uniqueId === item
							.uniqueId);

						if (target) {
							// 使用 Vue.set 确保响应式更新
							this.$set(target, 'remarks', content);

							// 更新当前页数据
							const currentPageIndex = this.currentPageData.findIndex(i => i.uniqueId === item
								.uniqueId);
							if (currentPageIndex !== -1) {
								this.currentPageData[currentPageIndex] = target;
							}

							// 清除所有缓存
							this.pageCache.clear();

							// 强制刷新分页器和视图
							this.$nextTick(() => {
								this.loadPageData(this.curPageNum);
								this.$forceUpdate();
							});

							console.log('备注更新成功：ID-${target.uniqueId} => ${content}');
						}
					}
				});
			},
			// handleRemark 方法修正
			setPersonnelName() {
				uni.showModal({
					title: '添加核查人员',
					content: this.orderList.checkPersonnelName,
					editable: true,
					success: ({
						content
					}) => {
						this.orderList.checkPersonnelName = content;
					}
				});
			},


		}
	}
</script>

<style lang="less" scoped>
	.page {
		background-color: #e9f1fe;
		padding: 20px;
	}

	.content {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.mpopup {
		background: #fff;
		overflow: hidden;

		&-body {

			/* 统一边框绘制 */
			&-thead,
			&-tbody-tr {
				border-left: 1px solid #757575;
				border-right: 1px solid #757575;
			}

			/* 表头优化 */
			&-thead {
				display: flex;
				background: #e9f1fe;
				border-bottom: 1px solid #757575;
				border-top: 1px solid #757575;

				&-name {
					width: 15%;
					min-width: 15%;
					border-right: 1px solid #757575;
					padding: 12px;
					box-sizing: border-box;
				}

				&-other {
					width: 85%;
					display: flex;

					&-unit,
					&-notAudit,
					&-timeOut,
					&-accumulative,
					&-file {
						flex: 1;
						padding: 12px;
						border-right: 1px solid #757575;
						box-sizing: border-box;
						text-align: center;

						&:last-child {
							border-right: none;
						}
					}

					/* 精确列宽分配 */
					&-unit {
						flex: 3;
					}

					/* 30% */
					&-notAudit {
						flex: 1;
					}

					/* 10% */
					&-timeOut {
						flex: 2;
					}

					/* 20% */
					&-accumulative {
						flex: 2;
					}

					/* 20% */
					&-file {
						flex: 1;
					}

					/* 10% */
				}


			}



			/* 表头优化 */
			&-thead2 {
				display: flex;
				background: #e9f1fe;

				border-top: 1px solid #757575;
				border-right: 1px solid #757575;
				border-left: 1px solid #757575;

				&-name {
					width: 15%;
					min-width: 15%;
					border-right: 1px solid #757575;
					padding: 12px;
					box-sizing: border-box;
				}

				&-name2 {
					width: 15%;
					min-width: 15%;
					border-right: 1px solid #757575;
					border-bottom: 1px solid #757575;
					padding: 12px;
					box-sizing: border-box;
				}

				&-name3 {
					width: 15%;
					min-width: 15%;
					border-right: 1px solid #757575;
					border-bottom: 1px solid #757575;
					display: flex;
					align-items: center;
					/* 垂直居中 */
					box-sizing: border-box;
				}

				&-other {
					width: 85%;
					display: flex;

					&-accumulative {
						flex: 1;
						padding: 12px;
						border-right: 1px solid #757575;
						box-sizing: border-box;
						text-align: center;
						background-color: #ffffff;

						&:last-child {
							border-right: none;
						}
					}

					&-accumulative2 {
						flex: 1;
						padding: 12px;
						border-right: 1px solid #757575;
						color: #0808ff;
						box-sizing: border-box;
						text-align: center;
						background-color: #ffffff;
						min-height: 150px;

						&:last-child {
							border-right: none;
						}
					}

					&-accumulative3 {
						flex: 1;
						padding: 12px;
						border-right: 1px solid #757575;
						border-bottom: 1px solid #757575;
						box-sizing: border-box;
						text-align: center;
						background-color: #ffffff;
						min-height: 150px;
						color: #0808ff;

						&:last-child {
							border-right: none;
						}
					}

					&-accumulative4 {
						flex: 1;
						padding: 12px;
						border-right: 1px solid #757575;
						border-bottom: 1px solid #757575;
						flex-direction: column;
						/* 垂直排列 */
						display: flex;
						justify-content: center;
						text-align: left;
						/* 垂直居中 */
						background-color: #ffffff;
						min-height: 150px;
						color: black;

					}
				}
			}

			/* 表体优化 */
			&-tbody {
				&-tr {
					display: flex;
					border-bottom: 1px solid #757575;

					&-name {
						width: 15%;
						min-width: 15%;
						padding: 12px;
						border-right: 1px solid #757575;
						box-sizing: border-box;
						background: #f8f9fa;
						font-size: 26px;
						display: flex;
						align-items: center;
					}

					&-other {
						width: 85%;
						display: flex;

						&-box {
							width: 100%;
							display: flex;

							&-unit,
							&-notAudit,
							&-timeOut,
							&-accumulative,
							&-file {
								flex: 1;
								padding: 12px;
								border-right: 1px solid #757575;
								box-sizing: border-box;
								min-height: 60px;
								display: flex;
								align-items: center;
								font-size: 17px;

								&:last-child {
									border-right: none;
								}
							}

							/* 保持与表头相同的列宽比例 */
							&-unit {
								flex: 3;
							}

							&-notAudit {
								flex: 1;
							}

							&-timeOut {
								flex: 2;
							}

							&-accumulative {
								flex: 2;
							}

							&-file {
								flex: 1;
							}
						}
					}
				}
			}
		}


	}

	.blank-page {
		padding: 1px; // 保持与其他页面一致的边距
		background-color: #e9f1fe;
	}

	.custom-title {
		display: flex;
		justify-content: center;
		align-items: center;
		margin-bottom: 10px;
		/* 保持原有下边距 */

	}

	.custom-title2 {
		display: flex;
		justify-content: center;
		align-items: center;
		margin-bottom: 10px;
		/* 保持原有下边距 */
		margin-top: 30px;
	}

	/* 日期行 */
	.date-row {
		display: flex;
		justify-content: flex-end;

		.date-item {
			position: relative;
			margin-left: 22rpx; // 项间距

			// 垂直排列容器
			&>* {
				display: block;
			}

			.edit-label {
				color: #2196F3;
				font-size: 16rpx;
				margin-left: 10px;
				margin-bottom: 3rpx; // 控制文字与下划线间距
			}

			.date-underline {
				width: 60rpx; // 固定下划线长度
				height: 2rpx;
				background: #333;
				position: relative;
			}

			.date-unit {
				position: absolute;
				right: -15rpx; // 单位右偏移量
				bottom: 5rpx; // 单位垂直位置
				font-size: 16rpx;
				color: #666;
				white-space: nowrap;
			}
		}
	}

	/* 多行文本处理 */
	.multiline-text {
		white-space: pre-wrap;
		word-break: break-word;
		line-height: 1.5;
	}

	/* 虚线容器 */
	.dashed-box {
		width: 100%;
		margin: 24rpx auto;
		padding: 32rpx;
		border: 2rpx dashed #333;
		border-radius: 10rpx;
		background: #fff;

		position: relative;

		&+.dashed-box {
			margin-top: 48rpx;
		}
	}


	/* 虚线容器 */
	.dashed-box2 {
		width: 100%;
		margin: 24rpx auto;
		padding: 12rpx;
		border: 2rpx dashed #333;
		border-radius: 10rpx;
		background: #fff;
		margin-bottom: 40px;
		position: relative;

		&+.dashed-box {
			margin-top: 28rpx;
		}
	}

	/* 虚线容器 */
	.dashed-box3 {
		width: 100%;
		border: 2rpx dashed #0055ff;
		border-radius: 10rpx;
		background: #e5ecff;
		height: 120px;
		/* 设置为flex布局 */
		display: flex;
		/* 水平居中 */
		justify-content: center;
		/* 垂直居中 */
		align-items: center;
	}

	/* 标题行 */
	.title-row2 {
		display: flex;
		justify-content: space-between;
		align-items: flex-end;
		margin-bottom: 68rpx;

		.title {
			margin-bottom: 20px;
		}

		.edit-btn {

			.btn-text {
				color: #2196F3;
				font-size: 16rpx;
				margin-left: 60px;
				margin-right: 16rpx;
			}


		}
	}

	/* 复选框居中 */
	.uni-data-checklist {
		justify-content: center !important;
	}


	.card-container {
		width: 100% !important;
		/* 覆盖潜在继承样式 */
		box-sizing: border-box;
		/* 包含padding计算 */
		margin-bottom: 10px; // 合并到类中
		padding: 5px;
		height: 200px;
		text-align: center;

	}

	.card-title {
		margin-bottom: 30px;
		font-size: 20px;
		margin-top: 20px;
		font-weight: bold;

		color: black;
	}

	.multi-input-container {
		padding: 15px;

		.uni-easyinput {
			margin-bottom: 10px;
			position: relative;

			.uni-icons {
				position: absolute;
				right: 10px;
				top: 50%;
				transform: translateY(-50%);
			}
		}

		.uni-icons[type="plus"] {
			display: block;
			text-align: center;
			margin-top: 10px;
		}
	}

	.card-content {
		font-size: 16px; // 默认字号，可按需调整
		color: #000;
		margin-bottom: 10px;

	}

	.custom-text {
		border-bottom: 1px solid #000;
		padding-bottom: 2px;
		padding-left: 15px;
		color: #0055ff;
		font-size: 20px;

		font-weight: bold;
		padding-right: 15px;
		margin-left: 4px;
		margin-right: 4px;
	}

	.custom-text2 {
		border-bottom: 1px solid #000;
		padding-bottom: 2px;
		padding-left: 20%;
		color: #0055ff;
		font-size: 16px;

		font-weight: bold;
		padding-right: 20%;
		margin-left: 4px;
		margin-right: 4px;
	}

	.custom-text3 {
		border-bottom: 1px solid #000;
		padding-bottom: 2px;
		padding-left: 10px;
		color: #0055ff;
		font-size: 16px;

		font-weight: bold;
		padding-right: 10px;
		margin-left: 4px;
		margin-right: 4px;
	}



	.custom-dateText {
		display: flex;
		margin: 20px;
		justify-content: flex-end;
		/* 子元素居左 */
	}


	/* 移动端适配 */
	@media (max-width: 768px) {
		.mpopup-body {
			overflow-x: auto;

			&-thead,
			&-tbody {
				min-width: 800px;
			}
		}
	}
</style>